<script lang="ts" setup>
import type { VxeGridListeners, VxeTableGridOptions } from '#/adapter/vxe-table'

import { onUnmounted, ref, watch } from 'vue'

import { Page, useVbenModal } from '@vben/common-ui'

import { Alert, Button, Input, message, Popconfirm, Space } from 'ant-design-vue'

import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { attrConfigDel, getAttrConfigList, sortable } from '#/api/attrConfig'

import popupForm from './info.vue'

const alertTxt = ref('')
const formOptions: any = {
  collapsed: true,
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  wrapperClass: 'grid-cols-5',
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'attr_name',
      label: '值',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'attr_key',
      label: '编码',
      operator: 'LIKE',
    },
  ],
  // 是否可展开
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
}
const gridOptions: VxeTableGridOptions = {
  checkboxConfig: {
    highlight: true,
    trigger: 'row',
  },
  rowConfig: {
    drag: true, // 总开关
    keyField: 'id', // 必须，用于拖拽排序后识别
  },

  height: 'auto',
  columns: [
    {
      type: 'checkbox', // 多选列（自带全选框）
      width: 50, // 列宽
      align: 'center', // 居中
      fixed: 'left', // 固定在最左侧
      title: '', // 表头文字
    },
    { title: '名称', field: 'attr_name', align: 'center', dragSort: true },
    { title: 'KEY', field: 'attr_key', align: 'center' },
    { title: '数据类型', field: 'data_type_name', align: 'center' },
    { title: '品类范围', field: 'cate_tag_str', align: 'center' },

    { title: '修改人', field: 'updateAdmin.realname', align: 'center' },
    { title: '创建人', field: 'createAdmin.realname', align: 'center' },
    { title: '修改时间', field: 'updated_at', align: 'center' },
    { title: '创建时间', field: 'created_at', align: 'center' },
    { title: '操作', field: 'action', fixed: 'right', slots: { default: 'action' } },
  ],
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const search = await gridApi.formApi.getFiltersValues()
        const res = await getAttrConfigList({
          page: page.currentPage,
          limit: page.pageSize,
          quick_search: quick_search.value,
          search,
        })
        alertTxt.value = res.remark
        return { items: res.list, total: res.total }
      },
    },
    sort: true,
  },
  id: 'attrConfig',
  customConfig: {
    storage: true,
  },
  toolbarConfig: {
    search: true,
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
}

// 双击打开编辑
const gridEvents: VxeGridListeners = {
  cellDblclick: ({ row }) => {
    openEdit(row, 'edit')
  },
  rowDragend({ dragRow, newRow, dragPos }) {
    // dragRow  被拖动的行数据
    // newRow   拖动到的目标行数据
    // dragPos  插入位置（'before' | 'after'）
    sortable({ id: dragRow.id, targetId: newRow.id }).then((res: any) => {
      if (res.data.code === 0) {
        message.error(res.data.msg)
      }
      gridApi.reload()
    })
  },
}
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
})

//  按钮的禁用状态
const isDisabled = ref(true)

// 检查并更新拷贝按钮状态
function checkCopyButtonStatus() {
  try {
    if (gridApi?.grid?.getCheckboxRecords) {
      const selectedRecords = gridApi.grid.getCheckboxRecords()
      // 检查是否包含已财务标记的记录
      isDisabled.value = !selectedRecords || selectedRecords.length === 0
    } else {
      isDisabled.value = true
    }
  } catch {
    isDisabled.value = true
  }
}

// 使用watch监听gridApi的变化
watch(
  () => gridApi?.grid,
  (newGrid) => {
    if (newGrid) {
      // 当grid可用时，立即检查一次状态
      checkCopyButtonStatus()
      // 设置一个定时器定期检查选中状态变化
      const interval = setInterval(() => {
        if (gridApi?.grid) {
          checkCopyButtonStatus()
        }
      }, 300) // 每300ms检查一次
      // 组件卸载时清除定时器
      onUnmounted(() => {
        clearInterval(interval)
      })
    }
  },
  { immediate: true },
)

function modelClose() {
  gridApi.reload()
}

const [popupFormModal, popupFormApi] = useVbenModal({
  connectedComponent: popupForm,
})

// 编辑
function openEdit(res: any, but: any) {
  popupFormApi.setData({ rowData: res.id, view: but }).open()
}
function openEdits() {
  const selectedRecords = gridApi.grid.getCheckboxRecords()
  if (selectedRecords.length === 0) {
    message.error('请选择数据')
    return
  }
  const data = selectedRecords.map((record: any) => record.id)
  popupFormApi.setData({ rowData: data, view: 'edit' }).open()
}

/**
 *  快速查询查询
 */
const quick_search = ref()
function doSearch() {
  gridApi.query()
}

// 删除
function delRow(id: any) {
  attrConfigDel({ ids: [id] }).then((res: any) => {
    if (res.data.code === 1) {
      message.success(res.data.msg)
      gridApi.reload()
    } else {
      message.error(res.data.msg)
    }
  })
}

// 删除
function delRows() {
  const data = gridApi.grid.getCheckboxRecords()

  attrConfigDel({ ids: data.map((record: any) => record.dict_id) }).then((res: any) => {
    if (res.data.code === 1) {
      message.success(res.data.msg)
      gridApi.reload()
    } else {
      message.error(res.data.msg)
    }
  })
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <div>
          <Space>
            <Button type="primary" @click="openEdit('', 'add')">新建</Button>
            <Button type="primary" @click="openEdits" :disabled="isDisabled">编辑</Button>
            <Button type="primary" danger @click="delRows()" :disabled="isDisabled">删除</Button>
            <Alert type="warning" closable show-icon>
              <template #message>
                <span v-html="alertTxt"></span>
              </template>
            </Alert>
          </Space>
        </div>
      </template>
      <template #toolbar-tools>
        <Input v-model:value="quick_search" allow-clear placeholder="通过id模糊搜索" style="width: 300px; margin-right: 8px" @change="doSearch" />
      </template>
      <template #action="{ row }">
        <Space>
          <Button type="primary" size="small" @click="openEdit(row, 'edit')"> 编辑 </Button>
          <Popconfirm title="确定删除选中记录？" ok-text="确认" cancel-text="取消" @confirm="delRow(row.id)">
            <Button type="primary" danger title="删除选中记录 ？" size="small">删除</Button>
          </Popconfirm>
        </Space>
      </template>
    </Grid>
    <popupFormModal @refresh="modelClose()" />
  </Page>
</template>
<style lang="scss" scoped>
.my-green-btn.ant-btn-primary {
  background-color: #67c23a;
  border-color: #67c23a;
}

.my-yello-btn.ant-btn-primary {
  background-color: #e6a23c;
  border-color: #e6a23c;
}
</style>
